import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Users, UsersDocument } from 'src/db/schemas/users.schema';
import { Model } from 'mongoose';
import { JwtService } from '@nestjs/jwt';
import { successData } from 'src/common/responses';
import { RegisterDto } from './dto';
import { HttpErrorException } from 'src/common/exceptions';
import { UsersDto } from 'src/db/dto';

@Injectable()
export class BaseService {
  constructor(
    @InjectModel(Users.name) private usersModel: Model<UsersDocument>,
    private readonly jwtService: JwtService,
  ) { }

  /**
   * 验证用户信息
   * @param username 用户名
   * @param password 密码
   * @returns 
   */
  async validateUser(username: string, password: string) {
    try {
      const userInfo = await this.usersModel.findOne({ username });
      if (userInfo && userInfo.password === password) {
        const { password, ...result } = userInfo.toJSON();
        return result;
      }
      return null
    } catch (error) {
      return null
    }
  }

  async login(user: UsersDto) {
    return successData({
      message: '登录成功',
      data: {
        token: this.jwtService.sign({
          username: user.username,
          _id: user._id,
        }),
      },
    });
  }

  async register(info: RegisterDto) {
    try {
      const {
        username,
        _id
      } = await new this.usersModel({
        ...info,
        // 注册默认为普通用户
        role: '63845371fdc1a266f965217e'
      }).save();
      return {
        message: '注册成功',
        data: {
          token: this.jwtService.sign({
            username,
            _id
          }),
        },
      }
    } catch (error: any) {
      throw new HttpErrorException(new Error(error).message);
    }
  }

  getMessage(): string {
    return 'Hello World';
  }
}
